﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Msung.Business.IService;
using Msung.Core;
using Msung.Core.Caching;
using Msung.Core.Extensions;
using Msung.Core.Kafka;
using Msung.Core.Kafka.Integration;
using Msung.Core.Snowflake;
using Msung.Repository.Entity;
using Newtonsoft.Json;
using DataTraceService.IService;
using DataTraceService.Model;
using Msung.Business.IService.MSUNG;
using Msung.Business.Model;
using Mapster;
using Msung.Business.Model.COLLECTION;
using Msung.Business.Service;
using Msung.Business.Model.TRACER;

namespace DataTraceService.Consumers
{
    public class RcaConsumerListener : IKafkaConsumerListener
    {
        readonly IRedisOperationRepository _redisRepository;
        readonly IFlowcardService _flowService;
        private readonly ILogger<RcaConsumerListener> _logger;

        public RcaConsumerListener(
            ILogger<RcaConsumerListener> logger,
            IRedisOperationRepository redisRepository,
            IFlowcardService flowService
            )
        {
            this._redisRepository = redisRepository;
            _logger = logger;
            _flowService = flowService;
        }
        public void ConsumeAsync(RecieveResult recieveResult)
        {
            _logger.logInfo($"RcaConsumerListener recieve message:{recieveResult.Message} location:{recieveResult.Offset} partition:{recieveResult.Partition} key:{recieveResult.Key} ");
            try
            {
                if (recieveResult.Message.Contains("料盒")) return;
                var model = recieveResult.GetRecieveMessage<RCA_MODEL>();
                if (model == null)
                {
                    return;
                }

                if (string.IsNullOrWhiteSpace(model.Struid) && string.IsNullOrWhiteSpace(model.FLAGPLC))
                {
                    recieveResult.Commit();
                    return;
                }
                if (string.IsNullOrWhiteSpace(model.Struid))
                {
                    model.Struid = $"{model.EID}_{DateTimeOffset.Now.ToUnixTimeSeconds()}";
                }

                DownBasketTask(model);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
            recieveResult.Commit();
        }
        #region 上/下花篮逻辑
        /// <summary>
        /// 切换下料花篮
        /// </summary>
        /// <param name="model"></param>
        public void DownBasketTask(RCA_MODEL model)
        {
            int a = 0;
            BasketModel basket = new BasketModel()
            {
                Eid = model.EID.ToString(),
                Pid = model.PID.ToString(),
                Buid = model.Struid,
                Struid = model.Struid,
                ChannelNo = int.TryParse(model.CHANEL, out a) ? a : 1,
                UpDown = model.UpDown,
                ProcessTime = model.CreatedTime,
                Status = "0"
            };

            string? flowNo = _redisRepository.Get($"FlowCard:{model.Struid}");
            flowNo = flowNo?.Replace("\"", "");

            FlowCardInput? flowInput = string.IsNullOrWhiteSpace(flowNo) ? null : _redisRepository.Get<FlowCardInput>("FlowNo:" + flowNo);
            string process = (int.Parse(model.PID) - 1).ToString();
            if (flowInput == null || int.Parse(flowInput.CURRENTPROCESS) >= int.Parse(model.PID))
            {
                string log = flowInput == null ? "null-" + flowNo : JsonConvert.SerializeObject(flowInput);
                _logger.LogDebug("RCA创建流程卡：" + log);
                flowInput = _flowService.CreateFlowCard(basket);
            }
            basket.WorkOrder = flowInput.WORKORDER;
            basket.ProductCode = flowInput.MATERIAL;
            basket.FlowNo = flowInput.FLOWNO;
            basket.WaferList = flowInput.Wafers;

            _flowService.FlowCardTrace(basket, flowInput);
        }

        #endregion
    }
}
